<template>
    <div class="transfer container">
      <h2>文件快传(Beta)</h2>
      <p>简单高效的文件传输服务(文件不大于100MB)</p>
      <a-tabs defaultActiveKey="1" size="large" style="text-align: center">
        <a-tab-pane key="1">
            <span slot="tab">
              <a-icon type="cloud" /> 上传
            </span>
            <div style="height: 300px;margin-top: 20px">
              <a-spin tip="上传中..." :spinning="spinning" size="large">
                <div class="spin-content">
                  <a-upload-dragger
                    name="file"
                    :multiple="false"
                    :supportServerRender="true"
                    :showUploadList="false"
                    :beforeUpload="beforeUpload"
                    :action="uploadUrl"
                    @change="handleChange">
                    <div style="display: flex;justify-content: center;align-items: center;height: 30vh">
                      <p class="ant-upload-drag-icon"></p>
                      <p class="ant-upload-text">点击或拖拽文件到此上传</p>
                      <p class="ant-upload-hint"></p>
                    </div>
                  </a-upload-dragger>
                </div>
              </a-spin>
              <div v-if="pickupCode" style="margin-top: 20px">
                <h2>取件码</h2>
                <span style="color: orangered">{{ pickupCode }}</span>
              </div>
            </div>
        </a-tab-pane>

        <a-tab-pane key="2" forceRender>
          <span slot="tab"><a-icon type="cloud-download" />获取</span>
          <div>
            <div style="display: flex;justify-content: center;align-items: center;height: 30vh">
              <a-input size="large" style="width: 200px" v-model="code">
                <span slot="prefix">取件码</span>
              </a-input>
            </div>

            <div>
              <a-button type="primary" shape="round" size="large" ghost @click="getTransfer">获取</a-button>
            </div>

            <a-modal
              title="文件详情"
              :visible="visible"
              @ok="handleOk"
              :okText="`下载`"
              :confirmLoading="confirmLoading"
              @cancel="handleCancel"
            >
              <div>
                <a-form-item label="下载地址">
                  <a-input v-model="file.downloadUrl" disabled  style="user-select: none"/>
                </a-form-item>
                <a-form-item label="过期时间">
                  <a-input v-model="file.expireDate" disabled />
                </a-form-item>
                <a-form-item label="下载次数">
                  <a-input v-model="file.downloadCounts" disabled />
                </a-form-item>
              </div>
            </a-modal>

          </div>

        </a-tab-pane>

      </a-tabs>
    </div>
</template>

<script>
  import app from "../../app";
  import { saveAs } from 'file-saver';
  const uploadUrl = `${app.api}/api/${app.apiVersion}/transfer/`;
  export default {
    name: "transfer",
    head: ()=>({
      title: "快传 - "+app.name,
      script: [
        { src: "https://cdnjs.cloudflare.com/ajax/libs/downloadjs/1.4.8/download.min.js"}
      ]
    }),
    data:()=>({
      spinning: false,
      uploadUrl,
      pickupCode: "",
      code: "",
      visible: false,
      confirmLoading: false,
      file: {
        downloadUrl: "",
        expireDate:"",
        downloadCounts:"",
        nickName:"",
        name: "",
      }
    }),
    methods: {
      beforeUpload(file){
        const isLt100M = file.size / 1024 / 1024 < 100;
        if (!isLt100M) {
          this.$message.error('文件必须小于100MB！嘿嘿！');
        }
        return isLt100M;
      },
      handleChange(info) {
        const status = info.file.status;
        if (status === 'uploading') {
          // 上传中
          this.spinning = true;
        } else if (status === 'done') {
          // 成功
          this.spinning = false;
          this.pickupCode = info.file.response.data;
          this.$message.success(`${info.file.name} 上传成功`);
        } else if (status === 'error') {
          // 失败
          this.spinning = false;
          this.$message.error(`${info.file.name} 上传失败`);
        }
      },
      getTransfer(e){
        if (!this.code) {
          this.$message.warning("请输入您的取件码")
        }else {
          this.$axios.$get(`${app.api}/api/${app.apiVersion}/transfer/`, { params: { code: this.code }})
            .then((resp)=>{
              console.log(resp)
              if (resp.code === 200) {
                this.visible = true
                this.file.name = resp.data.name
                this.file.nickName = resp.data.nickName
                this.file.expireDate = resp.data.expireDate
                this.file.downloadUrl = resp.data.downloadUrl
                this.file.downloadCounts = resp.data.downloadCounts
              }else {
                this.$message.warning(resp.msg)
              }
            }).catch((err)=>{

          })
        }
      },
      handleDownload(url, name) {
        this.getBlob(url).then(blob => {
          saveAs(blob, name);
        })
        return false;
      },
      getBlob(url) {
        return new Promise(resolve => {
          const xhr = new XMLHttpRequest();
          xhr.open('GET', url, true);
          xhr.responseType = 'blob';
          xhr.onload = () => {
            if (xhr.status === 200) {
              resolve(xhr.response);
            }
          };
          xhr.send();
        })
      },
      handleOk(){
        // 下载文件
        this.confirmLoading = true
        this.handleDownload(this.file.downloadUrl, this.file.name)
        this.confirmLoading = false
        this.visible = false;
        this.code = ""
      },
      handleCancel(){
        this.visible = false;
        this.confirmLoading = false;
        this.file.name = "";
        this.file.nickName = "";
        this.file.expireDate = "";
        this.file.downloadUrl = "";
        this.file.downloadCounts = ""
      }
    },
    mounted() {}
  }
</script>

<style scoped>
  .transfer{
    margin-top: 120px;
    min-height: 80vh;
  }
  @media screen and (max-width: 1023px){
    .transfer{
      margin-top: 70px;
      margin-left: 20px;
      margin-right: 20px;
    }
  }
</style>
